#!/usr/bin/env perl

use lib qw{../config ../lib/perl};
use strict;
use warnings;
use CGI;
use TRFLP;
use DBI;

my $cgi = new CGI;
my $key = $cgi->param('key');
my $tag = $cgi->param('tag');

print $cgi->header(-type => 'text/plain');

my $dbh = DBI->connect(
		       $TRFLP::dbconn,
		       $TRFLP::dbuser,
		       "",
		       {AutoCommit => 0, RaiseError => 0}
		      );
$DBI::state and do {
  print "ERROR: could not connect to the TRFLP database ($TRFLP::dbconn): $DBI::errstr";
  exit;
};

my ($type, $batch, $sample) = split ":", $key;

if ( $type eq 'batch' ) {
  my $query = qq(DELETE FROM batch_tag WHERE "set" = '$batch');
  $dbh->do($query);
  $dbh->err and do {
    print "ERROR: " . $dbh->errstr . " in query: [$query]";
    exit;
  };

  $query = qq(INSERT INTO batch_tag ("set", "key", "value") VALUES ('$batch', 'id', '$tag'));
  $dbh->do($query);
  $dbh->err and do {
    print "ERROR: " . $dbh->errstr . " in query: [$query]";
    exit;
  };
}
elsif ( $type eq 'sample' ) {
  my $query = qq(DELETE FROM sample_tag WHERE "set" = '$batch' AND "id" = '$sample');
  $dbh->do($query);
  $dbh->err and do {
    print "ERROR: " . $dbh->errstr . " in query: [$query]";
    exit;
  };

  # the last empty field was to be a value in a $tag -> $value pair (not implemented)
  $query = qq(INSERT INTO sample_tag ("set", "id", "key", "value") VALUES ('$batch', '$sample', '$tag', ''));
  $dbh->do($query);
  $dbh->err and do {
    print "ERROR: " . $dbh->errstr . " in query: [$query]";
    exit;
  };
}
else {
  print "ERROR: unknown key type: $type";
  exit;
}

$dbh->commit;
print "SUCCESS";
